package com.lhdx.practical.controllers;

import com.alibaba.fastjson.JSONObject;
import com.lhdx.practical.bean.*;
import com.lhdx.practical.dao.MenuDao;
import com.lhdx.practical.excelBean.ExcelStudent;
import com.lhdx.practical.excelBean.ExcelTeacher;
import com.lhdx.practical.service.DepartService;
import com.lhdx.practical.service.MenuConfigService;
import com.lhdx.practical.service.PersonService;
import com.lhdx.practical.service.StudentGroupService;
import com.lhdx.practical.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping("/function")
public class PersonController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private PersonService personService;
    @Autowired
    private DepartService departService;
    @Autowired
    private StudentGroupService studentGroupService;
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private MenuConfigService menuConfigService;

    /**
     * 个人信息
     * @return
     */
    @GetMapping("/person/information")
    public ModelAndView information() {
        long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
        Person person = personService.findById(userid);
        StudentGroup group = new StudentGroup();
        if(person.getIsjoin() != 0){
            group = studentGroupService.findById(person.getGroupid());
        }
        String urlpage = "person/information";
        String menuStr = "";
        if(person.getType() == 1){
            urlpage = "person/teacherInfo";
            long gradeid = StrUtils.getLong(request,"gradeid",0);
            List<MenuConfig> menuConfigs = menuConfigService.findAllByPersonidAndGradeid(person.getId(),gradeid);
            for(MenuConfig config : menuConfigs){
                menuStr += config.getMenuname()+"、";
            }
            if(menuStr.length() > 0){
                menuStr = menuStr.substring(0,menuStr.length()-1);
            }
        }
        return new ModelAndView(urlpage)
                .addObject("person",person)
                .addObject("group",group)
                .addObject("menuStr",menuStr);
    }
    /**
     * 导入学生信息页面
     * @return
     */
    @GetMapping("/person/teacherlist")
    public ModelAndView teacherlist() {
        List<Person> personList = personService.findAllByTypeAndGradeid(1,0);
        return new ModelAndView("person/teacherlist")
                .addObject("personList",personList);
    }

    /**
     * 修改密码
     * @return
     */
    @GetMapping("/person/changepass")
    public ModelAndView changepass() {
        return new ModelAndView("person/changepass");
    }

    /**
     * 导入学生信息页面
     * @return
     */
    @GetMapping("/person/importStudentInfo")
    public ModelAndView importStudentInfo(long departid) {
        Depart depart = new Depart();
        List<Depart> classdepart = new ArrayList<>();
        if(departid != 0){
            depart = departService.findById(departid);
            classdepart = departService.findAllByPid(depart.getPid());
        }
        return new ModelAndView("person/importStudentInfo")
                .addObject("depart",depart)
                .addObject("classdepart",classdepart)
                .addObject("grade",departService.findAllByPid(0));
    }

    /**
     * 导入老师信息页面
     * @return
     */
    @GetMapping("/person/importTeacherInfo")
    public ModelAndView importTeacherInfo() {
        return new ModelAndView("person/importTeacherInfo");
    }

    /**
     * 配置老师模块
     * @return
     */
    @GetMapping("/person/upModular")
    public ModelAndView upModular(long userid) {
        Person person = personService.findById(userid);
        return new ModelAndView("person/upModular")
                .addObject("person",person)
                .addObject("menuList",menuDao.findAllByPid(0));
    }

    /**
     * 修改老师模块
     * @return
     */
    @CrossOrigin
    @PostMapping("/person/updateModular")
    @ResponseBody
    public String updateModular(long userid,long menuid) {
        JSONObject jsonObject = new JSONObject();
        try {
            Person person = personService.findById(userid);
            Menu menu = menuDao.findById(menuid);
            if(person == null || menu == null){
                jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"设置失败","");
            }else{
                person.setDepartid(menu.getId());
                person.setDepartname(menu.getMenuname());
                personService.save(person);
                jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"设置成功","");
            }

        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"设置失败","");
        }
        return jsonObject.toString();
    }


    /**
     * 修改头像
     * @return
     */
    @CrossOrigin
    @PostMapping("/person/updateHeadimg")
    @ResponseBody
    public String updateHeadimg(String imgface) {
        JSONObject jsonObject = new JSONObject();
        try {
            long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
            personService.updateFaceImg(userid,imgface);
            jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"设置成功","");

        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"设置失败","");
        }
        return jsonObject.toString();
    }


    /**
     * 修改简介
     * @return
     */
    @CrossOrigin
    @PostMapping("/person/updateProfile")
    @ResponseBody
    public String updateProfile(String profile) {
        JSONObject jsonObject = new JSONObject();
        try {
            long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
            personService.updateProfile(userid,profile);
            jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"设置成功","");

        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"设置失败","");
        }
        return jsonObject.toString();
    }

    /**
     * 删除学生信息
     * @return
     */
    @CrossOrigin
    @PostMapping("/person/deletePerson")
    @ResponseBody
    public String deletePerson(long id) {
        JSONObject jsonObject = new JSONObject();
        try {
            personService.deleteById(id);
            jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"删除成功","");
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"删除失败","");
        }
        return jsonObject.toString();
    }

    /**
     * Excel导入老师信息
     * @return
     */
    @CrossOrigin
    @PostMapping("/person/upTeacherInfo")
    @ResponseBody
    public String upTeacherInfo(@RequestParam(value="file", required=false) MultipartFile file) {
        JSONObject jsonObject = new JSONObject();
        try {
            if (file != null && !file.isEmpty()) {
                if(file.getContentType().equals("application/vnd.ms-excel")){
                    List<ExcelTeacher> results = ExcelUtils.importExcel(file,1,1, ExcelTeacher.class);
                    Person person = null;
                    for(ExcelTeacher teacher : results){
                        if(personService.countByRealname(teacher.getRealname()) == 0){
                            person = new Person(teacher,1);
                            personService.save(person);
                        }
                    }
                    jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"导入成功","");
                }else{
                    jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"仅支持模版Excel文件","");
                }

            }else{
                jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"请选择文件","");
            }
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"信息导入失败","");
        }
        return jsonObject.toString();
    }


    /**
     * Excel导入学生信息
     * @return
     */
    @CrossOrigin
    @PostMapping("/person/upStudentInfo")
    @ResponseBody
    public String upStudentInfo(@RequestParam(value="file", required=false) MultipartFile file, long departid) {
        JSONObject jsonObject = new JSONObject();
        try {
            if (file != null && !file.isEmpty()) {
                if(file.getContentType().equals("application/vnd.ms-excel")){
                    List<ExcelStudent> results = ExcelUtils.importExcel(file,1,1, ExcelStudent.class);
                    Depart depart = departService.findById(departid);
                    Depart grade = departService.findById(depart.getPid());
                    Person person = null;
                    for(ExcelStudent student : results){
                        if(personService.countByRealname(student.getRealname()) == 0 && personService.countByUserno(student.getUserno()) == 0) {
                            person = new Person(student, depart, grade, 2);
                            personService.save(person);
                        }
                    }
                    jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"导入成功","");
                }else{
                    jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"仅支持模版Excel文件","");
                }
            }else{
                jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"请选择文件","");
            }
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"信息导入失败","");
        }
        return jsonObject.toString();
    }

    /**
     * 导出excel老师列表
     * @return
     */
    @CrossOrigin
    @RequestMapping(value = "/exportExcel", method = { RequestMethod.POST, RequestMethod.GET })
    @ResponseBody
    public String exportExcel(HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();
        try{
            List<Person> personList = personService.findAllByTypeAndGradeid(1,0);
            List<ExcelTeacher> results = new ArrayList<>();
            ExcelTeacher student = null;
            for(Person person : personList){
                student = new ExcelTeacher(person);
                results.add(student);
            }
            ExcelUtils.exportExcel(results,"老师信息","sheet1", ExcelTeacher.class,"老师信息导入模版.xls",response,request);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 修改密码
     * @return
     */
    @CrossOrigin
    @PostMapping("/person/tochangepass")
    @ResponseBody
    public String tochangepass(String password,String repass) {
        JSONObject jsonObject = new JSONObject();
        try {
            long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
            Person person = personService.findById(userid);
            //判断密码是否一致
            if(person.getPassword().equals(Md5Utils.md5(password))){
                //修改密码
                personService.updatePassword(userid,Md5Utils.md5(repass));
                jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"密码修改成功","");
            }else{
                jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"原密码错误","");
            }

        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"密码修改失败","");
        }
        return jsonObject.toString();
    }


    /**
     * 系统管理员重置密码
     * @return
     */
    @CrossOrigin
    @PostMapping("/person/repass")
    @ResponseBody
    public String repass(long id) {
        JSONObject jsonObject = new JSONObject();
        try {
            personService.updatePassword(id,Md5Utils.md5("111111"));
            jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"密码已重置为111111","");
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"密码重置失败","");
        }
        return jsonObject.toString();
    }


    /**
     * 按班级查找所有学生
     * @return
     */
    @GetMapping("/person/personlist")
    public ModelAndView personlist(long departid) {
        Depart depart = departService.findById(departid);
        int page = StrUtils.getInt(request,"p",1);
        Map<String,String> searchmap = new HashMap<>();
        searchmap.put("departid",departid+"");
        PageVo<Person> pageResult = new PageVo<Person>(page,searchmap,personService.getResultList(0,departid,2,page,Constants.pagesize));
        return new ModelAndView("person/personlist")
                .addObject("pageResult",pageResult)
                .addObject("depart",depart)
                .addObject("groupList",studentGroupService.findAllByDepartid(departid,2));
    }

    /**
     * 退出登录
     * @return
     */
    @CrossOrigin
    @GetMapping("/exit")
    public String exit(HttpServletResponse response) {
        try {
            CookieUtils.removeCookie(response,Constants.LOGINED);
            response.sendRedirect("/");
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查看签到情况
     * @return
     */
    @GetMapping("/person/sign")
    public ModelAndView sign(long mid,long sid,long gradeid) {
        int page = StrUtils.getInt(request,"p",1);
        Map<String,String> searchmap = new HashMap<>();
        searchmap.put("mid",mid+"");
        searchmap.put("sid",sid+"");
        searchmap.put("gradeid",gradeid+"");
        PageVo<Person> pageResult = new PageVo<Person>(page,searchmap,personService.getResultList(gradeid,0,2,page,Constants.pagesize));
        List<Person> personList = personService.findAllByTypeAndGradeid(2,gradeid);
        long current=System.currentTimeMillis();//当前时间毫秒数
        long  zero = current/(1000*3600*24)*(1000*3600*24)- TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
        int arrived = 0;    //已到
        int notarrived = 0; //未到
        for(Person p : personList){
            if(p.getLogintime() > zero){
                arrived++;
            }else{
                notarrived++;
            }
        }

        return new ModelAndView("person/sign")
                .addObject("personList",pageResult)
                .addObject("zero",zero)
                .addObject("arrived",arrived)
                .addObject("notarrived",notarrived);
    }

}
